/*
 *  Copyright (c) Skrumtious
 */
package com.skrumtious.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skrumtious.util.StringUtil;

/**
 * A web request
 * 
 * @author Tony
 *
 */
public class WebRequest {

	/**
	 * Request
	 */
	private HttpServletRequest request;
	
	/**
	 * Response
	 */
	private HttpServletResponse response;

	/**
	 * Get the userId
	 */
	private String userId;
	
	/**
	 * @param request
	 * @param response
	 */
	public WebRequest(HttpServletRequest request
					, HttpServletResponse response) {
		super();
		this.request = request;
		this.response = response;
		
		this.userId = "tonysparks";
	}
	
	/**
	 * @return the request
	 */
	public HttpServletRequest getRequest() {
		return request;
	}
	
	/**
	 * @return the response
	 */
	public HttpServletResponse getResponse() {
		return response;
	}
		
	/**
	 * Sets the bean on the {@link HttpServletRequest}.
	 * 
	 * @param beanName
	 * @param bean
	 */
	public void setBean(String beanName, Object bean) {		
		this.request.getSession().setAttribute(beanName, bean);
	}
	
	/**
	 * Gets a parameter as a string.
	 * 
	 * @param name
	 * @return
	 */
	public String getParamAsString(String name) {
		return this.request.getParameter(name);
	}
	
	/**
	 * Array delimeted by a ","
	 * @param name
	 * @return
	 */
	public String[] getParamAsStringArray(String name) {
		String result = getParamAsString(name);
		return result.split(",");
	}
	
	/**
	 * Converts the string array into an int[]
	 * @param name
	 * @return
	 */
	public int[] getParamAsIntArray(String name) {
		String[] strArray = getParamAsStringArray(name);
		int[] result = convertToIntArray(strArray);
		return result;
	}
	
	/**
	 * Converts the string array to an int array
	 * @param strArray
	 * @return
	 */
	private int[] convertToIntArray(String[] strArray) {
		int[] result = null;
		
		if ( strArray != null ) {
			result = new int[strArray.length];	
			for(int i = 0; i < strArray.length; i++ ) {
				result[i] = Integer.parseInt(strArray[i]);
			}
		}
		
		return result;
	}
	
	/**
	 * Parse the parameter as an integer
	 * @param name
	 * @return null if not a string or isn't present, otherwise an integer
	 */
	public Integer getParamAsInt(String name) {
		Integer result = null;
		
		String obj = this.request.getParameter(name);
		if ( ! StringUtil.isEmpty(obj) ) {
			try {
				result = Integer.parseInt(obj);
			}
			catch(Exception e) {
				result = null;
			}
		}
		
		return result;
	}
	
	/**
	 * @return gets the userId
	 */
	public String getUserId() {
		return this.userId;
	}
}
